package com.swu.pad.course.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swu.pad.course.dao.CourseGroupUserDao;
import com.swu.pad.course.dao.GroupDao;
import com.swu.pad.course.entity.CourseGroupUser;
import com.swu.pad.course.entity.Group;
import com.swu.pad.course.service.CourseGroupUserService;
import com.swu.pad.course.service.GroupService;
import com.swu.pad.util.StringUtil;
import com.swu.pad.util.EPLiteClient.EPLiteClient;

@Service
@Transactional
public class GroupServiceImpl implements GroupService {

	@Autowired
	private GroupDao groupDao;
	@Autowired
	private CourseGroupUserDao courseGroupUserDao;
	@Autowired
	private CourseGroupUserService courseGroupUserService;
	@Autowired
	private EPLiteClient epliteClient;

	public Group addGroup(Group group) {
		if (!StringUtil.isValid(group.getId())) {
			String groupName = group.getCourseId() + "$" + group.getGroupName();
			String authorId = epliteClient.createGroupIfNotExistsFor(groupName).get("groupID").toString();
			group.setId(authorId);
		}
		return groupDao.save(group);
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void deleteGroup(String groupId) {
		// 删除组，同时删除courseGroupUser
		List<CourseGroupUser> courseGroupUserList = courseGroupUserDao.findCourseGroupUserByGroupId(groupId);
		for (int i = 0; i < courseGroupUserList.size(); i++) {
			courseGroupUserService.deleteCourseGroupUser(courseGroupUserList.get(i).getId());
		}
		groupDao.delete(groupId);
	}

}
